#!/usr/bin/python
# -*- coding: UTF-8 -*-
# @License: Copyright © 2019 代鹏. All rights reserved.
# @Author: 代鹏
# @Contact: 272481080@qq.com
# @File: cu_mongodb.py
# @Date: 2019/6/18
# @Software：cu
# @description :
from app import app
import pymongo
import sys
import traceback

# MONGODB_CONFIG = {
#     'host': app.config.get('MONGODB_HOST'),
#     'port': app.config.get('MONGODB_PORT'),
#     'db_name': app.config.get('MONGODB_DB'),
#     'username': app.config.get('MONGODB_USERNAME'),
#     'password': app.config.get('MONGODB_PASSWORD')
# }
host = app.config.get('MONGODB_HOST')
port = app.config.get('MONGODB_PORT')
db_name = app.config.get('MONGODB_DB')
username = app.config.get('MONGODB_USERNAME')
password = app.config.get('MONGODB_PASSWORD')

class Singleton(object):
    # 单例模式写法,参考：http://ghostfromheaven.iteye.com/blog/1562618
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            orig = super(Singleton, cls)
            cls._instance = orig.__new__(cls, *args, **kwargs)
        return cls._instance


class MongoConn(Singleton):
    def __init__(self):
        # connect db
        try:
            self.conn = pymongo.MongoClient(host, port)
            self.db = self.conn[db_name]  # connect db
            self.username = username
            self.password = password
            if self.username and self.password:
                self.connected = self.db.authenticate(self.username, self.password)
            else:
                self.connected = True
        except Exception:
            print(traceback.format_exc())
            print('Connect Statics Database Fail.')
            sys.exit(1)
